<?php
namespace App\Http\Controllers\Admin;
use App\Models\Node;
use App\Models\Role;
use App\Models\RoleNode;

/**
 * RoleController.php
 * @author LF
 * @Date 16/7/9 11:28
 * @copyright Copyright© 2016-2016 飞煌科技
 * All Rights Reserved.
 * Code is poetry, thus is life.
 * @author JeffMing
 */
class RoleController extends BaseController{
    private $role_model;
    private $role_node_model;
    public function __construct()
    {
        parent::__construct();
        $this->role_model = new Role();
        $this->role_node_model = new RoleNode();
    }

    /***
     * 角色列表
     */
    public function getIndex(){
        $name = request('name');
        $where = array();
        if(!empty(trim($name))){
            $where['name'] = trim($name);
        }
        $fields = '*';
        $order = '';
        $pagesize = 20;
        $roles = $this->role_model->getList($where,$fields,$order,$pagesize);
        return view('admin.role.index',compact('roles','name'));
    }

    /***
     * 添加角色
     */
    public function getAdd(){
        $node_model = new Node();
        $where['pid'] = array('>',0);
        $nodes = $node_model->getAllData($where);
        return view('admin.role.form',compact('nodes'));
    }

    public function postAdd(){
        $data = request()->except('_token');
        $res = $this->role_model->add($data);
        if(!$res){
            return redirect()->action(NAMESPACE_ADMIN.'RoleController@getAdd');
        }
        return redirect()->action(NAMESPACE_ADMIN.'RoleController@getIndex');
    }

    /***
     * 修改角色
     */
    public function getEdit($id){
        $role = $this->role_model->getOne(['id'=>$id]);
        $nodes = $this->role_model->getEditNodes($id,['url'=>['!=','']]);
        return view('admin.role.form',compact('role','nodes'));
    }


    public function postEdit(){
        $id = request('id');
        $data = request()->except('_token');
        $res = $this->role_model->upRole($id,$data);
        if($res){
            return redirect()->action(NAMESPACE_ADMIN.'RoleController@getIndex');
        }
        return redirect($_SERVER['HTTP_REFERER']);
    }

    /***
     * @param $id
     * 删除数据
     */
    public function getDel($id){
       $res =  $this->role_model->del($id);
       return redirect(action(NAMESPACE_ADMIN.'RoleController@getIndex'));
    }
}